<template>
  <div class="table-management">
    <div class="page-header">
      <h1>数据表管理</h1>
      <p class="page-description">选择数据源和数据库后管理其下的数据表，支持创建、修改和删除表结构</p>
    </div>

    <!-- 数据源和数据库选择器 -->
    <div class="selector-section">
      <el-card shadow="never" class="selector-card">
        <div class="selector-content">
          <div class="selector-item">
            <div class="selector-label">
              <el-icon><DataBoard /></el-icon>
              <span>数据源:</span>
            </div>
            <el-select
              v-model="selectedDataSourceId"
              placeholder="请选择数据源"
              style="width: 250px"
              @change="handleDataSourceChange"
              :loading="loadingDataSources"
            >
              <el-option
                v-for="ds in dataSources"
                :key="ds.id"
                :label="`${ds.name} (${getDatabaseTypeText(ds.type)})`"
                :value="ds.id"
              />
            </el-select>
          </div>

          <div class="selector-item">
            <div class="selector-label">
              <el-icon><Collection /></el-icon>
              <span>数据库:</span>
            </div>
            <el-select
              v-model="selectedDatabaseName"
              placeholder="请选择数据库"
              style="width: 250px"
              @change="handleDatabaseChange"
              :loading="loadingDatabases"
              :disabled="!selectedDataSourceId"
            >
              <el-option
                v-for="db in databases"
                :key="db.name"
                :label="db.name"
                :value="db.name"
              />
            </el-select>
          </div>

          <el-button @click="refreshAll" :icon="Refresh" :loading="loadingTables">
            刷新
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 表管理区域 -->
    <div v-if="selectedDataSource && selectedDatabaseName" class="table-section">
      <div class="section-header">
        <div class="section-title">
          <h2>{{ selectedDataSource.name }} / {{ selectedDatabaseName }} - 数据表</h2>
          <el-tag type="info">{{ tables.length }} 个表</el-tag>
        </div>
        <div class="section-actions">
          <el-button type="primary" @click="showCreateTableDialog" :icon="Plus">
            创建表
          </el-button>
          <el-button @click="importTable" :icon="Upload">
            导入表
          </el-button>
          <el-button @click="exportTables" :icon="Download">
            导出表
          </el-button>
        </div>
      </div>

      <div class="toolbar">
        <div class="search-area">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索表名"
            :prefix-icon="Search"
            clearable
            style="width: 300px"
          />
        </div>
        <div class="filter-area">
          <el-select v-model="tableTypeFilter" placeholder="表类型" style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="基础表" value="BASE TABLE" />
            <el-option label="视图" value="VIEW" />
            <el-option label="临时表" value="TEMPORARY" />
          </el-select>
        </div>
      </div>

      <div class="table-list">
        <el-table
          :data="filteredTables"
          v-loading="loadingTables"
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column prop="name" label="表名" min-width="200">
            <template #default="{ row }">
              <div class="table-name-cell">
                <el-icon class="table-icon">
                  <Grid v-if="row.type === 'BASE TABLE'" />
                  <View v-else-if="row.type === 'VIEW'" />
                  <Document v-else />
                </el-icon>
                <span class="table-name">{{ row.name }}</span>
                <el-tag v-if="row.type === 'VIEW'" type="success" size="small">视图</el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="comment" label="备注" min-width="150">
            <template #default="{ row }">
              <span class="table-comment">{{ row.comment || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="rowCount" label="行数" width="100" align="right">
            <template #default="{ row }">
              <span class="row-count">{{ formatNumber(row.rowCount) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="dataSize" label="数据大小" width="120" align="right">
            <template #default="{ row }">
              <span class="data-size">{{ formatSize(row.dataSize) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="engine" label="存储引擎" width="100">
            <template #default="{ row }">
              <el-tag size="small" :type="getEngineTagType(row.engine)">
                {{ row.engine || '-' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              <span class="create-time">{{ formatDate(row.createTime) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click="viewTableStructure(row)">
                  结构
                </el-button>
                <el-button size="small" @click="viewTableData(row)">
                  数据
                </el-button>
                <el-dropdown @command="handleTableCommand">
                  <el-button size="small" :icon="MoreFilled" />
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="{action: 'edit', table: row}">
                        <el-icon><Edit /></el-icon>
                        编辑表
                      </el-dropdown-item>
                      <el-dropdown-item :command="{action: 'copy', table: row}">
                        <el-icon><CopyDocument /></el-icon>
                        复制表
                      </el-dropdown-item>
                      <el-dropdown-item :command="{action: 'truncate', table: row}" divided>
                        <el-icon><Delete /></el-icon>
                        清空数据
                      </el-dropdown-item>
                      <el-dropdown-item :command="{action: 'drop', table: row}">
                        <el-icon><Delete /></el-icon>
                        删除表
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 批量操作 -->
      <div v-if="selectedTables.length > 0" class="batch-actions">
        <el-card shadow="never">
          <div class="batch-content">
            <span class="batch-info">已选择 {{ selectedTables.length }} 个表</span>
            <div class="batch-buttons">
              <el-button @click="batchExport">批量导出</el-button>
              <el-button @click="batchTruncate" type="warning">批量清空</el-button>
              <el-button @click="batchDrop" type="danger">批量删除</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty description="请先选择数据源和数据库">
        <el-button type="primary" @click="goToDataSourceManagement">
          去管理数据源
        </el-button>
      </el-empty>
    </div>

    <!-- 创建表对话框 -->
    <el-dialog
      v-model="createTableDialogVisible"
      title="创建数据表"
      width="800px"
      @close="resetCreateTableForm"
    >
      <el-form
        ref="createTableFormRef"
        :model="createTableFormData"
        :rules="createTableFormRules"
        label-width="100px"
      >
        <el-form-item label="表名" prop="name">
          <el-input
            v-model="createTableFormData.name"
            placeholder="请输入表名"
          />
        </el-form-item>
        
        <el-form-item 
          v-if="currentDatabaseType === 'mysql'" 
          label="存储引擎" 
          prop="engine"
        >
          <el-select v-model="createTableFormData.engine" style="width: 200px">
            <el-option 
              v-for="engine in availableEngines" 
              :key="engine.value"
              :label="engine.label" 
              :value="engine.value" 
            />
          </el-select>
        </el-form-item>

        <el-form-item label="字符集" prop="charset">
          <el-select v-model="createTableFormData.charset" style="width: 200px">
            <el-option 
              v-for="charset in availableCharsets" 
              :key="charset.value"
              :label="charset.label" 
              :value="charset.value" 
            />
          </el-select>
        </el-form-item>

        <!-- PostgreSQL 特有选项 -->
        <el-form-item 
          v-if="currentDatabaseType === 'postgresql'" 
          label="表空间" 
          prop="tablespace"
        >
          <el-select v-model="createTableFormData.tablespace" style="width: 200px" placeholder="默认表空间">
            <el-option label="pg_default" value="pg_default" />
            <el-option label="pg_global" value="pg_global" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="createTableFormData.comment"
            type="textarea"
            :rows="2"
            placeholder="请输入表备注（可选）"
          />
        </el-form-item>

        <el-form-item label="字段定义">
          <div class="columns-definition">
            <div class="columns-header">
              <el-button type="primary" size="small" @click="addColumn">
                添加字段
              </el-button>
            </div>
            <el-table :data="createTableFormData.columns" style="width: 100%">
              <el-table-column prop="name" label="字段名" width="150">
                <template #default="{ row, $index }">
                  <el-input v-model="row.name" size="small" />
                </template>
              </el-table-column>
              <el-table-column prop="type" label="类型" width="150">
                <template #default="{ row, $index }">
                  <el-select v-model="row.type" size="small" @change="onColumnTypeChange(row, $index)">
                    <el-option-group
                      v-for="category in groupedDataTypes"
                      :key="category.name"
                      :label="category.label"
                    >
                      <el-option
                        v-for="type in category.types"
                        :key="type.value"
                        :label="type.label"
                        :value="type.value"
                      />
                    </el-option-group>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="length" label="长度" width="80">
                <template #default="{ row, $index }">
                  <el-input 
                    v-model="row.length" 
                    size="small" 
                    :disabled="!getDataTypeInfo(row.type)?.hasLength"
                    :placeholder="getDataTypeInfo(row.type)?.hasLength ? '长度' : '无需长度'"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="nullable" label="允许空" width="80">
                <template #default="{ row, $index }">
                  <el-checkbox v-model="row.nullable" />
                </template>
              </el-table-column>
              <el-table-column prop="defaultValue" label="默认值" width="100">
                <template #default="{ row, $index }">
                  <el-input v-model="row.defaultValue" size="small" />
                </template>
              </el-table-column>
              <el-table-column prop="domainCode" label="数据域" width="120">
                <template #default="{ row, $index }">
                  <el-select v-model="row.domainCode" size="small" clearable placeholder="选择数据域" @change="onDomainChange(row, $index)">
                    <el-option
                      v-for="domain in dataDomains"
                      :key="domain.code"
                      :label="domain.name"
                      :value="domain.code"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="dictionaryCode" label="数据字典" width="140">
                <template #default="{ row, $index }">
                  <el-select 
                    v-model="row.dictionaryCode" 
                    size="small" 
                    clearable 
                    placeholder="选择数据字典"
                    @change="onDictionaryChange(row, $index)"
                  >
                    <el-option
                      v-for="dict in getFilteredDictionaries(row.domainCode)"
                      :key="dict.code"
                      :label="dict.name"
                      :value="dict.code"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="comment" label="备注" width="120">
                <template #default="{ row, $index }">
                  <el-input v-model="row.comment" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="60">
                <template #default="{ row, $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeColumn($index)"
                    :icon="Delete"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="createTableDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createTable" :loading="creatingTable">
            创建
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Search,
  Upload,
  Download,
  MoreFilled,
  Edit,
  Delete,
  CopyDocument,
  DataBoard,
  Collection,
  Grid,
  View,
  Document
} from '@element-plus/icons-vue'
import { dataTableApi } from '@/api/dataTable.js'
import { dataDictionaryApi } from '@/api/dataDictionary.js'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loadingDataSources = ref(false)
const loadingDatabases = ref(false)
const loadingTables = ref(false)
const creatingTable = ref(false)
const selectedDataSourceId = ref(null)
const selectedDatabaseName = ref('')
const searchKeyword = ref('')
const tableTypeFilter = ref('')
const selectedTables = ref([])
const createTableDialogVisible = ref(false)
const createTableFormRef = ref()

// 数据源列表
const dataSources = ref([
  {
    id: 1,
    name: '主数据库',
    type: 'mysql',
    host: 'localhost',
    port: 3306,
    status: 'connected'
  },
  {
    id: 2,
    name: '测试数据库',
    type: 'postgresql',
    host: '192.168.1.100',
    port: 5432,
    status: 'connected'
  }
])

// 数据库列表
const databases = ref([])

// 表列表
const tables = ref([])

// 数据域列表
const dataDomains = ref([
  { code: 'USER', name: '用户域' },
  { code: 'PRODUCT', name: '商品域' },
  { code: 'ORDER', name: '订单域' },
  { code: 'SYSTEM', name: '系统域' }
])

// 数据字典列表
const dataDictionaries = ref([
  {
    code: 'USER_NAME',
    name: '用户姓名',
    domainCode: 'USER',
    dataType: 'VARCHAR',
    length: 50,
    required: true,
    pattern: '^[\u4e00-\u9fa5a-zA-Z]{2,20}$',
    defaultValue: '',
    example: '张三'
  },
  {
    code: 'PHONE_NUMBER',
    name: '手机号码',
    domainCode: 'USER',
    dataType: 'VARCHAR',
    length: 11,
    required: true,
    pattern: '^1[3-9]\\d{9}$',
    defaultValue: '',
    example: '13800138000'
  },
  {
    code: 'PRODUCT_NAME',
    name: '商品名称',
    domainCode: 'PRODUCT',
    dataType: 'VARCHAR',
    length: 200,
    required: true,
    pattern: '',
    defaultValue: '',
    example: 'iPhone 15 Pro Max'
  },
  {
    code: 'PRODUCT_PRICE',
    name: '商品价格',
    domainCode: 'PRODUCT',
    dataType: 'DECIMAL',
    length: 10,
    precision: 2,
    required: true,
    pattern: '',
    defaultValue: '0.00',
    example: '9999.00'
  },
  {
    code: 'ORDER_STATUS',
    name: '订单状态',
    domainCode: 'ORDER',
    dataType: 'VARCHAR',
    length: 20,
    required: true,
    pattern: '^(pending|paid|shipped|delivered|cancelled)$',
    defaultValue: 'pending',
    example: 'paid'
  }
])

// 数据库类型特有配置
const databaseTypeConfigs = {
  mysql: {
    engines: [
      { label: 'InnoDB', value: 'InnoDB' },
      { label: 'MyISAM', value: 'MyISAM' },
      { label: 'Memory', value: 'Memory' },
      { label: 'Archive', value: 'Archive' }
    ],
    charsets: [
      { label: 'utf8mb4', value: 'utf8mb4' },
      { label: 'utf8', value: 'utf8' },
      { label: 'latin1', value: 'latin1' },
      { label: 'gbk', value: 'gbk' }
    ],
    dataTypes: [
      // 数值类型
      { label: 'TINYINT', value: 'TINYINT', category: 'numeric', hasLength: true },
      { label: 'SMALLINT', value: 'SMALLINT', category: 'numeric', hasLength: true },
      { label: 'MEDIUMINT', value: 'MEDIUMINT', category: 'numeric', hasLength: true },
      { label: 'INT', value: 'INT', category: 'numeric', hasLength: true },
      { label: 'BIGINT', value: 'BIGINT', category: 'numeric', hasLength: true },
      { label: 'DECIMAL', value: 'DECIMAL', category: 'numeric', hasLength: true },
      { label: 'FLOAT', value: 'FLOAT', category: 'numeric', hasLength: true },
      { label: 'DOUBLE', value: 'DOUBLE', category: 'numeric', hasLength: true },
      // 字符串类型
      { label: 'CHAR', value: 'CHAR', category: 'string', hasLength: true },
      { label: 'VARCHAR', value: 'VARCHAR', category: 'string', hasLength: true },
      { label: 'TINYTEXT', value: 'TINYTEXT', category: 'string', hasLength: false },
      { label: 'TEXT', value: 'TEXT', category: 'string', hasLength: false },
      { label: 'MEDIUMTEXT', value: 'MEDIUMTEXT', category: 'string', hasLength: false },
      { label: 'LONGTEXT', value: 'LONGTEXT', category: 'string', hasLength: false },
      // 日期时间类型
      { label: 'DATE', value: 'DATE', category: 'datetime', hasLength: false },
      { label: 'TIME', value: 'TIME', category: 'datetime', hasLength: false },
      { label: 'DATETIME', value: 'DATETIME', category: 'datetime', hasLength: false },
      { label: 'TIMESTAMP', value: 'TIMESTAMP', category: 'datetime', hasLength: false },
      { label: 'YEAR', value: 'YEAR', category: 'datetime', hasLength: false },
      // 二进制类型
      { label: 'BINARY', value: 'BINARY', category: 'binary', hasLength: true },
      { label: 'VARBINARY', value: 'VARBINARY', category: 'binary', hasLength: true },
      { label: 'BLOB', value: 'BLOB', category: 'binary', hasLength: false },
      // JSON类型
      { label: 'JSON', value: 'JSON', category: 'json', hasLength: false }
    ]
  },
  postgresql: {
    engines: [], // PostgreSQL 不使用存储引擎概念
    charsets: [
      { label: 'UTF8', value: 'UTF8' },
      { label: 'LATIN1', value: 'LATIN1' },
      { label: 'SQL_ASCII', value: 'SQL_ASCII' }
    ],
    dataTypes: [
      // 数值类型
      { label: 'SMALLINT', value: 'SMALLINT', category: 'numeric', hasLength: false },
      { label: 'INTEGER', value: 'INTEGER', category: 'numeric', hasLength: false },
      { label: 'BIGINT', value: 'BIGINT', category: 'numeric', hasLength: false },
      { label: 'DECIMAL', value: 'DECIMAL', category: 'numeric', hasLength: true },
      { label: 'NUMERIC', value: 'NUMERIC', category: 'numeric', hasLength: true },
      { label: 'REAL', value: 'REAL', category: 'numeric', hasLength: false },
      { label: 'DOUBLE PRECISION', value: 'DOUBLE PRECISION', category: 'numeric', hasLength: false },
      { label: 'SERIAL', value: 'SERIAL', category: 'numeric', hasLength: false },
      { label: 'BIGSERIAL', value: 'BIGSERIAL', category: 'numeric', hasLength: false },
      // 字符串类型
      { label: 'CHAR', value: 'CHAR', category: 'string', hasLength: true },
      { label: 'VARCHAR', value: 'VARCHAR', category: 'string', hasLength: true },
      { label: 'TEXT', value: 'TEXT', category: 'string', hasLength: false },
      // 日期时间类型
      { label: 'DATE', value: 'DATE', category: 'datetime', hasLength: false },
      { label: 'TIME', value: 'TIME', category: 'datetime', hasLength: false },
      { label: 'TIMESTAMP', value: 'TIMESTAMP', category: 'datetime', hasLength: false },
      { label: 'TIMESTAMPTZ', value: 'TIMESTAMPTZ', category: 'datetime', hasLength: false },
      { label: 'INTERVAL', value: 'INTERVAL', category: 'datetime', hasLength: false },
      // 布尔类型
      { label: 'BOOLEAN', value: 'BOOLEAN', category: 'boolean', hasLength: false },
      // 二进制类型
      { label: 'BYTEA', value: 'BYTEA', category: 'binary', hasLength: false },
      // JSON类型
      { label: 'JSON', value: 'JSON', category: 'json', hasLength: false },
      { label: 'JSONB', value: 'JSONB', category: 'json', hasLength: false },
      // 数组类型
      { label: 'ARRAY', value: 'ARRAY', category: 'array', hasLength: false },
      // UUID类型
      { label: 'UUID', value: 'UUID', category: 'uuid', hasLength: false }
    ]
  }
}

// 创建表单数据
const createTableFormData = reactive({
  name: '',
  engine: 'InnoDB',
  charset: 'utf8mb4',
  tablespace: '', // PostgreSQL 表空间
  comment: '',
  columns: [
    {
      name: 'id',
      type: 'INT',
      length: '11',
      nullable: false,
      defaultValue: '',
      comment: '主键ID',
      domainCode: '',
      dictionaryCode: ''
    }
  ]
})

// 创建表单验证规则
const createTableFormRules = computed(() => {
  const rules = {
    name: [
      { required: true, message: '请输入表名', trigger: 'blur' },
      { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '表名只能包含字母、数字和下划线，且以字母开头', trigger: 'blur' }
    ],
    charset: [
      { required: true, message: '请选择字符集', trigger: 'change' }
    ]
  }
  
  // 只有 MySQL 需要验证存储引擎
  if (currentDatabaseType.value === 'mysql') {
    rules.engine = [
      { required: true, message: '请选择存储引擎', trigger: 'change' }
    ]
  }
  
  return rules
})

// 计算属性
const selectedDataSource = computed(() => {
  return dataSources.value.find(ds => ds.id === selectedDataSourceId.value)
})

const currentDatabaseType = computed(() => {
  return selectedDataSource.value?.type || 'mysql'
})

const currentTypeConfig = computed(() => {
  return databaseTypeConfigs[currentDatabaseType.value] || databaseTypeConfigs.mysql
})

const availableDataTypes = computed(() => {
  return currentTypeConfig.value.dataTypes || []
})

const availableEngines = computed(() => {
  return currentTypeConfig.value.engines || []
})

const availableCharsets = computed(() => {
  return currentTypeConfig.value.charsets || []
})

const groupedDataTypes = computed(() => {
  const categoryLabels = {
    numeric: '数值类型',
    string: '字符串类型',
    datetime: '日期时间类型',
    boolean: '布尔类型',
    binary: '二进制类型',
    json: 'JSON类型',
    array: '数组类型',
    uuid: 'UUID类型'
  }
  
  const groups = {}
  availableDataTypes.value.forEach(type => {
    const category = type.category || 'other'
    if (!groups[category]) {
      groups[category] = {
        name: category,
        label: categoryLabels[category] || '其他类型',
        types: []
      }
    }
    groups[category].types.push(type)
  })
  
  return Object.values(groups)
})

const getDataTypeInfo = (typeValue) => {
  return availableDataTypes.value.find(type => type.value === typeValue)
}

const onColumnTypeChange = (row, index) => {
  const typeInfo = getDataTypeInfo(row.type)
  if (typeInfo && !typeInfo.hasLength) {
    row.length = ''
  }
}

// 根据数据域筛选数据字典
const getFilteredDictionaries = (domainCode) => {
  if (!domainCode) {
    return dataDictionaries.value
  }
  return dataDictionaries.value.filter(dict => dict.domainCode === domainCode)
}

// 数据字典变化时自动填充字段属性
const onDictionaryChange = (row, index) => {
  if (!row.dictionaryCode) return
  
  const dictionary = dataDictionaries.value.find(dict => dict.code === row.dictionaryCode)
  if (dictionary) {
    // 自动填充字段属性
    row.type = dictionary.dataType
    row.length = dictionary.length?.toString() || ''
    row.nullable = !dictionary.required
    row.defaultValue = dictionary.defaultValue || ''
    
    // 如果字段名为空，可以建议使用字典的示例名称
    if (!row.name) {
      row.name = dictionary.code.toLowerCase()
    }
    
    // 如果备注为空，使用字典的名称作为备注
    if (!row.comment) {
      row.comment = dictionary.name
    }
    
    ElMessage.success(`已根据数据字典"${dictionary.name}"自动填充字段属性`)
  }
}

// 数据域变化时的处理
const onDomainChange = (row, index) => {
  // 如果当前选择的数据字典不属于新的数据域，清空数据字典选择
  if (row.dictionaryCode && row.domainCode) {
    const dictionary = dataDictionaries.value.find(dict => dict.code === row.dictionaryCode)
    if (dictionary && dictionary.domainCode !== row.domainCode) {
      row.dictionaryCode = ''
      ElMessage.info('数据域已更改，已清空不匹配的数据字典选择')
    }
  }
}

// 验证数据域和数据字典的关联
const validateDataDomainAndDictionary = () => {
  const errors = []
  
  createTableFormData.columns.forEach((column, index) => {
    const fieldName = column.name || `字段${index + 1}`
    
    // 如果选择了数据字典，验证数据字典是否存在
    if (column.dictionaryCode) {
      const dictionary = dataDictionaries.value.find(dict => dict.code === column.dictionaryCode)
      if (!dictionary) {
        errors.push(`${fieldName}的数据字典"${column.dictionaryCode}"不存在`)
        return
      }
      
      // 验证数据字典是否属于选择的数据域
      if (column.domainCode && dictionary.domainCode !== column.domainCode) {
        const domainName = dataDomains.value.find(d => d.code === column.domainCode)?.name || column.domainCode
        errors.push(`${fieldName}的数据字典不属于所选数据域"${domainName}"`)
      }
      
      // 验证字段类型是否与数据字典匹配
      if (column.type !== dictionary.dataType) {
        errors.push(`${fieldName}的数据类型"${column.type}"与数据字典要求的"${dictionary.dataType}"不匹配`)
      }
      
      // 验证字段长度是否符合数据字典要求
      if (dictionary.length && column.length && parseInt(column.length) > dictionary.length) {
        errors.push(`${fieldName}的长度"${column.length}"超过数据字典允许的最大长度"${dictionary.length}"`)
      }
      
      // 验证必填字段
      if (dictionary.required && column.nullable) {
        errors.push(`${fieldName}根据数据字典要求不能为空`)
      }
    }
    
    // 如果选择了数据域但没有选择数据字典，给出提示
    if (column.domainCode && !column.dictionaryCode) {
      const domainName = dataDomains.value.find(d => d.code === column.domainCode)?.name || column.domainCode
      // 这里只是警告，不阻止创建
      console.warn(`${fieldName}选择了数据域"${domainName}"但未选择数据字典，建议选择相应的数据字典以确保数据标准化`)
    }
  })
  
  return errors
}

// 验证字段定义的基本规则
const validateColumnDefinition = () => {
  const errors = []
  const columnNames = new Set()
  
  createTableFormData.columns.forEach((column, index) => {
    const fieldName = column.name || `字段${index + 1}`
    
    // 验证字段名称
    if (!column.name) {
      errors.push(`第${index + 1}个字段缺少字段名`)
    } else {
      // 验证字段名格式
      if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(column.name)) {
        errors.push(`字段"${column.name}"名称格式不正确，只能包含字母、数字和下划线，且以字母开头`)
      }
      
      // 验证字段名唯一性
      if (columnNames.has(column.name.toLowerCase())) {
        errors.push(`字段名"${column.name}"重复`)
      } else {
        columnNames.add(column.name.toLowerCase())
      }
    }
    
    // 验证数据类型
    if (!column.type) {
      errors.push(`字段"${fieldName}"缺少数据类型`)
    }
    
    // 验证长度字段
    const typeInfo = availableDataTypes.value.find(t => t.value === column.type)
    if (typeInfo?.hasLength && !column.length) {
      errors.push(`字段"${fieldName}"的数据类型"${column.type}"需要指定长度`)
    }
  })
  
  return errors
}

const filteredTables = computed(() => {
  let result = tables.value
  
  if (searchKeyword.value) {
    result = result.filter(table => 
      table.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  if (tableTypeFilter.value) {
    result = result.filter(table => table.type === tableTypeFilter.value)
  }
  
  return result
})

// 方法
const getDatabaseTypeText = (type) => {
  const typeMap = {
    mysql: 'MySQL',
    postgresql: 'PostgreSQL',
    sqlserver: 'SQL Server',
    oracle: 'Oracle'
  }
  return typeMap[type] || type
}

const formatNumber = (num) => {
  if (!num) return '0'
  return num.toLocaleString()
}

const formatSize = (size) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let index = 0
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024
    index++
  }
  return `${size.toFixed(1)} ${units[index]}`
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

const getEngineTagType = (engine) => {
  const typeMap = {
    'InnoDB': 'success',
    'MyISAM': 'warning',
    'Memory': 'info'
  }
  return typeMap[engine] || ''
}

const handleDataSourceChange = (dataSourceId) => {
  selectedDatabaseName.value = ''
  tables.value = []
  if (dataSourceId) {
    loadDatabases(dataSourceId)
  } else {
    databases.value = []
  }
}

const handleDatabaseChange = (databaseName) => {
  if (databaseName && selectedDataSourceId.value) {
    loadTables(selectedDataSourceId.value, databaseName)
  } else {
    tables.value = []
  }
}

const loadDatabases = async (dataSourceId) => {
  loadingDatabases.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 800))
    
    const mockDatabases = {
      1: [
        { name: 'ecommerce' },
        { name: 'user_center' },
        { name: 'logs' }
      ],
      2: [
        { name: 'test_db' },
        { name: 'analytics' }
      ]
    }
    
    databases.value = mockDatabases[dataSourceId] || []
  } catch (error) {
    ElMessage.error('加载数据库列表失败')
  } finally {
    loadingDatabases.value = false
  }
}

const loadTables = async (dataSourceId, databaseName) => {
  loadingTables.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟表数据
    const mockTables = [
      {
        name: 'users',
        type: 'BASE TABLE',
        comment: '用户表',
        rowCount: 15420,
        dataSize: 1024 * 1024 * 2.5, // 2.5MB
        engine: 'InnoDB',
        createTime: '2024-01-15T10:30:00Z'
      },
      {
        name: 'products',
        type: 'BASE TABLE',
        comment: '产品表',
        rowCount: 8932,
        dataSize: 1024 * 1024 * 5.2, // 5.2MB
        engine: 'InnoDB',
        createTime: '2024-01-20T14:20:00Z'
      },
      {
        name: 'orders',
        type: 'BASE TABLE',
        comment: '订单表',
        rowCount: 45678,
        dataSize: 1024 * 1024 * 12.8, // 12.8MB
        engine: 'InnoDB',
        createTime: '2024-02-01T09:15:00Z'
      },
      {
        name: 'user_stats',
        type: 'VIEW',
        comment: '用户统计视图',
        rowCount: 0,
        dataSize: 0,
        engine: null,
        createTime: '2024-02-15T16:45:00Z'
      },
      {
        name: 'temp_data',
        type: 'TEMPORARY',
        comment: '临时数据表',
        rowCount: 1234,
        dataSize: 1024 * 512, // 512KB
        engine: 'Memory',
        createTime: '2024-03-01T11:00:00Z'
      }
    ]
    
    tables.value = mockTables
  } catch (error) {
    ElMessage.error('加载表列表失败')
  } finally {
    loadingTables.value = false
  }
}

const refreshAll = async () => {
  if (selectedDataSourceId.value) {
    await loadDatabases(selectedDataSourceId.value)
    if (selectedDatabaseName.value) {
      await loadTables(selectedDataSourceId.value, selectedDatabaseName.value)
    }
    ElMessage.success('数据已刷新')
  }
}

const handleSelectionChange = (selection) => {
  selectedTables.value = selection
}

const showCreateTableDialog = () => {
  createTableDialogVisible.value = true
  resetCreateTableForm()
}

const resetCreateTableForm = () => {
  const dbType = currentDatabaseType.value
  const config = currentTypeConfig.value
  
  // 根据数据库类型设置默认值
  const defaultEngine = config.engines.length > 0 ? config.engines[0].value : ''
  const defaultCharset = config.charsets.length > 0 ? config.charsets[0].value : ''
  const defaultIdType = dbType === 'postgresql' ? 'SERIAL' : 'INT'
  const defaultIdLength = dbType === 'postgresql' ? '' : '11'
  
  Object.assign(createTableFormData, {
    name: '',
    engine: defaultEngine,
    charset: defaultCharset,
    tablespace: '',
    comment: '',
    columns: [
      {
        name: 'id',
        type: defaultIdType,
        length: defaultIdLength,
        nullable: false,
        defaultValue: '',
        comment: '主键ID',
        domainCode: '',
        dictionaryCode: ''
      }
    ]
  })
  if (createTableFormRef.value) {
    createTableFormRef.value.clearValidate()
  }
}

const addColumn = () => {
  createTableFormData.columns.push({
    name: '',
    type: 'VARCHAR',
    length: '255',
    nullable: true,
    defaultValue: '',
    comment: '',
    domainCode: '',
    dictionaryCode: ''
  })
}

const removeColumn = (index) => {
  if (createTableFormData.columns.length > 1) {
    createTableFormData.columns.splice(index, 1)
  } else {
    ElMessage.warning('至少需要保留一个字段')
  }
}

const createTable = async () => {
  if (!createTableFormRef.value) return
  
  try {
    await createTableFormRef.value.validate()
    
    if (createTableFormData.columns.length === 0) {
      ElMessage.warning('请至少添加一个字段')
      return
    }
    
    // 验证字段定义的基本规则
    const columnErrors = validateColumnDefinition()
    if (columnErrors.length > 0) {
      ElMessage.error(`字段定义验证失败：${columnErrors.join(', ')}`)
      return
    }
    
    // 验证数据域和数据字典的关联
    const validationErrors = validateDataDomainAndDictionary()
    if (validationErrors.length > 0) {
      ElMessage.error(`数据域和数据字典验证失败：${validationErrors.join(', ')}`)
      return
    }
    
    creatingTable.value = true
    
    // 模拟创建表
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    const dbType = currentDatabaseType.value
    const newTable = {
      name: createTableFormData.name,
      type: 'BASE TABLE',
      comment: createTableFormData.comment,
      rowCount: 0,
      dataSize: 0,
      databaseType: dbType,
      createTime: new Date().toISOString(),
      // 根据数据库类型添加特有属性
      ...(dbType === 'mysql' && { 
        engine: createTableFormData.engine,
        charset: createTableFormData.charset 
      }),
      ...(dbType === 'postgresql' && { 
        tablespace: createTableFormData.tablespace || 'pg_default',
        encoding: createTableFormData.charset 
      })
    }
    
    tables.value.push(newTable)
    
    // 根据数据库类型显示不同的成功消息
    let successMessage = `表 "${createTableFormData.name}" 创建成功`
    if (dbType === 'mysql') {
      successMessage += ` (引擎: ${createTableFormData.engine}, 字符集: ${createTableFormData.charset})`
    } else if (dbType === 'postgresql') {
      const tablespace = createTableFormData.tablespace || 'pg_default'
      successMessage += ` (表空间: ${tablespace}, 编码: ${createTableFormData.charset})`
    }
    
    ElMessage.success(successMessage)
    createTableDialogVisible.value = false
  } catch {
    ElMessage.warning('请完善表单信息')
  } finally {
    creatingTable.value = false
  }
}

const viewTableStructure = (table) => {
  ElMessage.info(`查看表 "${table.name}" 的结构...`)
  // 这里可以打开表结构查看对话框
}

const viewTableData = (table) => {
  ElMessage.info(`查看表 "${table.name}" 的数据...`)
  // 这里可以打开数据查看页面
}

const handleTableCommand = ({ action, table }) => {
  switch (action) {
    case 'edit':
      editTable(table)
      break
    case 'copy':
      copyTable(table)
      break
    case 'truncate':
      truncateTable(table)
      break
    case 'drop':
      dropTable(table)
      break
  }
}

const editTable = (table) => {
  ElMessage.info(`编辑表 "${table.name}" 功能开发中...`)
}

const copyTable = async (table) => {
  try {
    const { value: newTableName } = await ElMessageBox.prompt(
      `请输入新表名（复制自 "${table.name}"）`,
      '复制表',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
        inputErrorMessage: '表名格式不正确'
      }
    )
    
    ElMessage.success(`表 "${table.name}" 已复制为 "${newTableName}"`)
    // 这里添加到表列表
  } catch {
    // 用户取消
  }
}

const truncateTable = async (table) => {
  try {
    await ElMessageBox.confirm(
      `确定要清空表 "${table.name}" 的所有数据吗？此操作不可恢复！`,
      '清空表数据',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.success(`表 "${table.name}" 数据已清空`)
  } catch {
    // 用户取消
  }
}

const dropTable = async (table) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除表 "${table.name}" 吗？此操作不可恢复，将删除表结构和所有数据！`,
      '删除表',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    const index = tables.value.findIndex(t => t.name === table.name)
    if (index > -1) {
      tables.value.splice(index, 1)
      ElMessage.success(`表 "${table.name}" 已删除`)
    }
  } catch {
    // 用户取消
  }
}

const importTable = () => {
  ElMessage.info('导入表功能开发中...')
}

const exportTables = () => {
  ElMessage.info('导出表功能开发中...')
}

const batchExport = () => {
  ElMessage.info(`批量导出 ${selectedTables.value.length} 个表...`)
}

const batchTruncate = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要清空选中的 ${selectedTables.value.length} 个表的数据吗？`,
      '批量清空',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.success(`已清空 ${selectedTables.value.length} 个表的数据`)
    selectedTables.value = []
  } catch {
    // 用户取消
  }
}

const batchDrop = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedTables.value.length} 个表吗？此操作不可恢复！`,
      '批量删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    selectedTables.value.forEach(table => {
      const index = tables.value.findIndex(t => t.name === table.name)
      if (index > -1) {
        tables.value.splice(index, 1)
      }
    })
    
    ElMessage.success(`已删除 ${selectedTables.value.length} 个表`)
    selectedTables.value = []
  } catch {
    // 用户取消
  }
}

const goToDataSourceManagement = () => {
  router.push({ name: 'DataSourceManagement' })
}

// 监听路由参数变化
watch(() => route.query, (newQuery) => {
  if (newQuery.dataSourceId) {
    selectedDataSourceId.value = parseInt(newQuery.dataSourceId)
    handleDataSourceChange(selectedDataSourceId.value)
  }
  if (newQuery.databaseName) {
    selectedDatabaseName.value = newQuery.databaseName
    if (selectedDataSourceId.value) {
      loadTables(selectedDataSourceId.value, newQuery.databaseName)
    }
  }
}, { immediate: true })

onMounted(() => {
  // 组件挂载后的初始化逻辑
})
</script>

<style scoped>
.table-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-description {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.selector-section {
  margin-bottom: 24px;
}

.selector-card {
  border: 1px solid #e5e7eb;
}

.selector-content {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}

.selector-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.selector-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #374151;
  white-space: nowrap;
}

.table-section {
  margin-top: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.section-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
}

.section-actions {
  display: flex;
  gap: 12px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px;
}

.search-area {
  flex: 1;
}

.filter-area {
  display: flex;
  gap: 12px;
}

.table-list {
  margin-bottom: 20px;
}

.table-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-icon {
  color: #8b5cf6;
}

.table-name {
  font-weight: 500;
}

.table-comment {
  color: #6b7280;
}

.row-count,
.data-size,
.create-time {
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 13px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.batch-actions {
  margin-top: 16px;
}

.batch-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-info {
  font-weight: 500;
  color: #374151;
}

.batch-buttons {
  display: flex;
  gap: 12px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.columns-definition {
  width: 100%;
}

.columns-header {
  margin-bottom: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .selector-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .selector-item {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>